<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="背景音乐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入背景音乐名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input
          v-model="queryParams.leader"
          placeholder="请输入负责人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="背景音乐状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['resource:bgm:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList">
      <el-table-column prop="shopName" label="商户名称"></el-table-column>
      <el-table-column prop="audioUrl" label="BGM信息" width="500px">
        <template slot-scope="scope">
          <a-player :music="scope.row.audio" :autoplay="false" />
                   <!-- <a :href="scope.row.audioUrl" target="_blank" style="color: #00afff;">{{scope.row.audioUrl}}</a> -->
        </template>
      </el-table-column>
<!--      <el-table-column prop="title" label="视频标题"></el-table-column>-->
<!--      <el-table-column prop="durationStr" label="播放时长" width="100px"></el-table-column>-->
<!--      <el-table-column prop="shopName" label="商户名称"/>-->
      <el-table-column prop="status" label="状态" width="100px">

        <template slot-scope="scope">

          <span v-if="scope.row.status == 0">启用</span>
          <span v-if="scope.row.status == 1">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="global" label="是否全局" width="100px">
        <template slot-scope="scope">

          <span v-if="scope.row.global == 0">是</span>
          <span v-if="scope.row.global == 1">否</span>

        </template>
      </el-table-column>

      <el-table-column prop="tags" label="标签">
        <template slot-scope="scope">
          <div v-if="scope.row.tags != null">
            <el-tag v-for="tag in scope.row.tags" :key="tag.value">{{tag.label}}</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['resource:bgm:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"

          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改背景音乐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :show-close="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="音乐标题" prop="title" label-width="100px">
              <el-input v-model="form.title" placeholder="音乐标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="source" label-width="100px">
              <el-select
                v-model.number="form.status"
                placeholder="状态"
                clearable
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签" prop="tags" label-width="100px">
              <el-select v-model="form.tags"
                         multiple
                         placeholder="请选择">
                <el-option
                  v-for="item in tagsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传资源">
              <fileUpload
                :action="action"
                v-model="form.audioUrl"
                @delUrl="delFileUrl"
                :fileType="['mp3']"></fileUpload>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { list, addMusic, editMusic, getMusic, uploadMusic, delMusic } from '@/api/music/list'
import { packagelist } from '@/api/package/package'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listDeptExcludeChild } from '@/api/system/dept'
import { listUser } from '@/api/merchant/merchant'
import fileUpload from '@/components/FileUpload/index'
import { deleteProxyUser } from '@/api/acting/user'
import __config from '../../config/env'
import { info } from '@/api/resource/resource'
import { getSelectTags } from '@/api/tag/tag'
import APlayer from 'vue-aplayer'
import {deleteFile} from  '@/api/resource/resource'

export default {
  name: 'music',
  components: {fileUpload, APlayer},
  data() {
    return {
      action: __config.musicAction,
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      orderList: [],
      // 背景音乐树选项
      actingOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //详情接口弹窗
      infoOpen: false,
      //订单详情信息表格数据
      infoList: [],
      //商户列表
      shopList: [],
      // 状态数据字典
      total: 0,
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // source: [{required: true, message: '该选项不能为空', trigger: 'blur'}],
        parentId: [
          { required: true, message: '上级背景音乐不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '背景音乐名称不能为空', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '显示排序不能为空', trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: '\'请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]

      },
      //套餐列表
      comboList: [],
      //标签列表
      tagsOptions: [],

      audio: {},
      //保存删除文件url地址
      deleteFileUrl:[]

    }
  },
  created() {
    //
    this.getList()
    // this.getCombo()
    this.getDicts('system_status').then(response => {
      this.statusOptions = response.data
      this.statusOptions.forEach(item => {
        item.dictValue = Number(item.dictValue)
      })
    })

  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    /** 查询背景音乐列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
        this.total = response.total
        this.orderList = response.rows;
        this.orderList.forEach(item =>{
          item.audio.artist = "未知";
          delete item.audio.pic
        })
        this.loading = false
      })
    },
    //查询套餐列表
    getCombo() {
      packagelist().then(res => {
        this.comboList = res.rows
      })
    },

    //查看支付结果
    PayStatus(row) {
      getPayStatus(row.id).then(res => {
      })

    },
      //获取音乐标签
    getTags(id){
      getSelectTags({
        shopId:id
      }).then(res => {
        this.tagsOptions = res.data
      })
    },
    //搜索商户
    remoteMethod(query) {
      listUser({
        shopName: query
      }).then(res => {
        this.shopList = res.rows
      })

    },
    //套餐列表选中时将套餐名称赋予form中
    comboChange(e) {
      let getNameObj = this.comboList.find(function(item) {
        return item.id == e
      })
      this.form.goodsName = getNameObj.name
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    //上传成功回调
    uploadSuccess(e) {
    },
    //获取删除url地址
    delFileUrl(url){
      this.deleteFileUrl.push(url);

      this.form.audioUrl = "";
    },
    //删除文件
    delFile(url){
      deleteFile(url).then(res =>{
        this.deleteFileUrl.forEach((item,index) =>{
          if (item == url){
            this.deleteFileUrl.splice(index,1)
          }
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false

      //如果在新增操作中上传了文件没有点保存点击了取消 删除刚刚上传的文件
      if (this.form.id == undefined && this.form.audioUrl){
        this.delFile(this.form.audioUrl);
      }
      //判断是否是新增资源操作 如果是将删除之前 删除文件(deleteFileUrl)列表中的资源
      if (this.deleteFileUrl.length > 0 && this.form.id == undefined){
        this.deleteFileUrl.forEach((item,index) =>{
          this.delFile(item);
        })
      }
      //在修改情况下，如果点击删除操作上传一个新文件但是点了取消操作 将删除新文件地址不删除原文件地址
      if(this.form.id && this.form.audioUrl){
        if (this.deleteFileUrl.length > 0){
          this.delFile(this.form.audioUrl);
        }
      }

      // 判断是否是修改资源操作
      if (this.deleteFileUrl.length > 0 && this.form.id != undefined){
        this.deleteFileUrl.forEach((item,index) =>{
          //如果是修改操作点击取消将不删除最后一条数据
          if (this.deleteFileUrl.length != index +1){
            this.delFile(item);
          }
        })
      }
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm('form');
      this.deleteFileUrl = [];

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row != undefined) {
        this.form.parentId = row.id
      }
      // if("rolesKey == '00'"){
      //   this.getTags(0)
      // }else{
      //   this.getTags()
      // }
      this.getTags()
      this.open = true
      this.title = '新增背景音乐'
      this.form.status = 0

    },
    //查询订单详情
    getInfo(row) {
      this.infoOpen = true
      getMusic(row.orderNum).then(res => {
        this.infoList.push(res.data)
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.getTags(row.id)
      getMusic(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改资源'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            editMusic(this.form).then(res => {
              this.delUploadList();
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMusic(this.form).then(response => {
              this.msgSuccess('新增成功');
              this.delUploadList();
              this.open = false
              this.getList()
            })
          }

        }
      })
    },
    //点击保存是循环删除废弃文件列表
    delUploadList(){
      //如果上传上传参数有值并且删除文件列表数量大于0的时候 将删除文件列表里面的资源
      console.log(this.form.audioUrl && this.deleteFileUrl.length)
      console.log(this.form.audioUrl , this.deleteFileUrl)
      if (this.form.audioUrl && this.deleteFileUrl.length > 0){
        console.log("我执行了")
        this.deleteFileUrl.forEach((item,index) =>{
          this.delFile(item);
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids.toString()
      this.$confirm('是否确认删除bgm id为"' + id + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delMusic(id)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
      })
    }
  }
}
</script>
